<?php

namespace app\common\model;

use think\Model;

/**
 * RedemptionCodeBatch 兑换码批次模型
 */
class RedemptionCodeBatch extends Model
{
    // 表名
    protected $name = 'redemption_code_batch';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 状态常量 - 与数据库字段一致
    const STATUS_DISABLED = '0';  // 禁用
    const STATUS_ACTIVE = '1';    // 启用
    const STATUS_COMPLETED = '2'; // 已完成

    /**
     * 关联兑换码
     * @return \think\model\relation\HasMany
     */
    public function redemptionCodes(): \think\model\relation\HasMany
    {
        return $this->hasMany(RedemptionCode::class, 'batch_id', 'id');
    }

    /**
     * 获取使用率
     * @return float
     */
    public function getUsageRateAttr(): float
    {
        return $this->total_count > 0 ? round($this->used_count / $this->total_count * 100, 2) : 0;
    }

    // /**
    //  * 生成兑换码
    //  * @param int $batchId 批次ID
    //  * @param int $count 生成数量
    //  * @param string $prefix 前缀
    //  * @param int $length 长度
    //  * @return array 生成的兑换码数组
    //  */
    // public function generateRedemptionCodes(int $batchId, int $count, string $prefix = '', int $length = RedemptionCode::DEFAULT_CODE_LENGTH): array
    // {
    //     $codes = [];
    //     $batch = self::find($batchId);
        
    //     if (!$batch) {
    //         throw new \Exception('批次不存在');
    //     }
        
    //     for ($i = 0; $i < $count; $i++) {
    //         $code = RedemptionCode::generateUniqueCode($prefix, $length);
            
    //         // 创建兑换码记录
    //         $redemptionCode = new RedemptionCode();
    //         $redemptionCode->save([
    //             'batch_id' => $batchId,
    //             'code' => $code,
    //             'title' => $batch->title,
    //             'description' => $batch->description,
    //             'type' => $batch->max_uses_per_code > 1 ? 'multiple' : 'single',
    //             'discount_amount' => $batch->discount_amount,
    //             'discount_percent' => $batch->discount_percent,
    //             'max_uses' => $batch->max_uses_per_code,
    //             'used_count' => 0,
    //             'start_time' => $batch->start_time,
    //             'end_time' => $batch->end_time,
    //             'status' => RedemptionCode::STATUS_ACTIVE,
    //             'admin_id' => $batch->admin_id,
    //             'create_time' => time(),
    //             'update_time' => time(),
    //         ]);
            
    //         $codes[] = $code;
    //     }
        
    //     return $codes;
    // }
}